import router from './router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import { asyncRotes } from '@/router'
const whiteList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
  nprogress.start()
  if (store.getters.token) {
    // 存在token
    if (to.path === '/login') {
      // 跳转到主页
      next('/') // 中转到主页
      nprogress.done()
    } else {
      // 判断是否获取过资料
      if (!store.getters.userId) {
        // 初始化执行
        const { roles } = await store.dispatch('user/getUserInfo')
        // console.log(roles.menus) // 数组不确定 可能是8个 1个 0个
        // console.log(asyncRotes)// 数组 8 个
        const filterRoutes = asyncRotes.filter((item) => {
          return roles.menus.includes(item.name)
        }) // 筛选后的路由
        store.commit('user/setRouts', filterRoutes)
        router.addRoutes([
          ...filterRoutes,
          { path: '*', redirect: '/404', hidden: true }
        ]) // 添加动态路由信息到路由表
        // router 添加动态路由之后需要转发一下
        next(to.path) // 目的是让路由拥有信息 router的已知缺陷
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login') // 中转到登录页
      nprogress.done()
    }
    // 没有token
    next()
  }
})

router.afterEach(() => {
  nprogress.done()
})
